package org.convallaria.infrastruct.db.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.convallaria.infrastruct.db.util.ExceptionAnalyzer;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;

/**
 * 高性能慢SQL拦截器
 * 
 * 功能特性：
 * - 智能SQL执行监控与统计
 * - 可配置慢查询阈值和日志级别
 * - 支持SQL参数解析和记录
 * - 线程安全的执行统计
 * - 性能优化设计（纳秒级精度、缓存优化）
 * 
 * @author gjh
 * @since 2024-09-24
 */
@Slf4j
@Intercepts({
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class SlowSqlInterceptor implements Interceptor {

    // ===== 配置参数 =====
    
    private volatile long slowSqlThreshold = 1000L;
    private volatile boolean enableSqlLog = true;
    private volatile boolean logParameters = false;
    private volatile String logLevel = "WARN";
    private volatile int maxSqlLength = 1000;
    private volatile boolean enableStatistics = true;

    // ===== 统计信息 =====
    
    private final ConcurrentHashMap<String, SqlStatistics> sqlStatistics = new ConcurrentHashMap<>();
    private final AtomicLong totalExecutions = new AtomicLong(0);
    private final AtomicLong slowQueryCount = new AtomicLong(0);
    private final AtomicLong totalExecutionTime = new AtomicLong(0);

    // ===== 缓存和优化 =====
    
    private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final int STATISTICS_CACHE_SIZE = 1000; // 限制统计缓存大小

    /**
     * SQL执行统计信息
     */
    private static class SqlStatistics {
        private final AtomicLong count = new AtomicLong(0);
        private final AtomicLong totalTime = new AtomicLong(0);
        private final AtomicLong slowCount = new AtomicLong(0);
        private volatile long maxTime = 0;
        private volatile long minTime = Long.MAX_VALUE;
        private volatile long lastExecuteTime = System.currentTimeMillis();

        public void addExecution(long executeTime, boolean isSlow) {
            count.incrementAndGet();
            totalTime.addAndGet(executeTime);
            lastExecuteTime = System.currentTimeMillis();
            
            if (isSlow) {
                slowCount.incrementAndGet();
            }

            // 更新最大最小时间（使用无锁设计）
            updateMinMax(executeTime);
        }

        private void updateMinMax(long executeTime) {
            // 更新最大时间
            long currentMax;
            do {
                currentMax = maxTime;
                if (executeTime <= currentMax) {
                    break;
                }
            } while (!compareAndSetMaxTime(currentMax, executeTime));

            // 更新最小时间
            long currentMin;
            do {
                currentMin = minTime;
                if (executeTime >= currentMin) {
                    break;
                }
            } while (!compareAndSetMinTime(currentMin, executeTime));
        }

        private synchronized boolean compareAndSetMaxTime(long expect, long update) {
            if (maxTime == expect) {
                maxTime = update;
                return true;
            }
            return false;
        }

        private synchronized boolean compareAndSetMinTime(long expect, long update) {
            if (minTime == expect) {
                minTime = update;
                return true;
            }
            return false;
        }

        public double getAverageTime() {
            long c = count.get();
            return c > 0 ? (double) totalTime.get() / c : 0;
        }

        public double getSlowRatio() {
            long c = count.get();
            return c > 0 ? (double) slowCount.get() / c * 100 : 0;
        }

        public long getLastExecuteTime() {
            return lastExecuteTime;
        }
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 快速路径：如果不需要任何监控，直接执行
        if (!enableSqlLog && slowSqlThreshold <= 0 && !enableStatistics) {
            return invocation.proceed();
        }

        final long startTime = System.nanoTime();
        String methodId = null;
        Object result = null;
        Throwable exception = null;
        String sqlInfo = null;
        
        try {
            // 安全地获取方法标识和SQL信息
            try {
                MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
                methodId = mappedStatement.getId();
                
                // 预获取SQL信息，便于异常时记录
                if (invocation.getArgs().length > 1) {
                    Object parameter = invocation.getArgs()[1];
                    BoundSql boundSql = mappedStatement.getBoundSql(parameter);
                    sqlInfo = truncateSql(formatSql(boundSql.getSql()));
                }
            } catch (Exception e) {
                log.debug("获取SQL元信息时发生异常，将继续执行: {}", e.getMessage());
                methodId = "unknown";
                sqlInfo = "SQL获取失败";
            }
            
            // 执行SQL
            result = invocation.proceed();
            return result;
            
        } catch (Throwable e) {
            exception = e;
            // 记录SQL执行异常的详细信息
            logSqlException(methodId, sqlInfo, e, System.nanoTime() - startTime);
            throw e;
        } finally {
            final long endTime = System.nanoTime();
            final long executeTime = (endTime - startTime) / 1_000_000; // 转换为毫秒
            
            // 安全地处理统计和日志
            safeProcessExecutionResult(invocation, methodId, executeTime, result, exception);
        }
    }

    /**
     * 安全地处理SQL执行结果
     */
    private void safeProcessExecutionResult(Invocation invocation, String methodId, 
                                          long executeTime, Object result, Throwable exception) {
        try {
            processExecutionResult(invocation, methodId, executeTime, result, exception);
        } catch (Exception e) {
            // 确保拦截器本身的异常不影响业务，但要记录详细日志
            log.error("处理SQL执行结果时发生严重异常 - 方法: {}, 执行时间: {}ms, 原始异常: {}", 
                methodId, executeTime, exception != null ? exception.getClass().getSimpleName() : "无", e);
            
            // 尝试至少更新基本统计
            try {
                totalExecutions.incrementAndGet();
                totalExecutionTime.addAndGet(executeTime);
                if (executeTime >= slowSqlThreshold) {
                    slowQueryCount.incrementAndGet();
                }
            } catch (Exception ignored) {
                // 连基本统计都失败了，只能忽略
            }
        }
    }

    /**
     * 记录SQL执行异常
     */
    private void logSqlException(String methodId, String sqlInfo, Throwable exception, long executeTimeNanos) {
        if (!enableSqlLog) {
            return;
        }
        
        try {
            long executeTimeMs = executeTimeNanos / 1_000_000;
            
            // 使用异常分析器分析异常
            ExceptionAnalyzer.ExceptionType exceptionType = ExceptionAnalyzer.analyzeException(
                exception, sqlInfo, methodId);
            
            String exceptionTypeName = exception != null ? exception.getClass().getSimpleName() : "Unknown";
            String exceptionMessage = exception != null ? exception.getMessage() : "无异常信息";
            
            // 截断异常消息避免日志过长
            if (exceptionMessage != null && exceptionMessage.length() > 200) {
                exceptionMessage = exceptionMessage.substring(0, 200) + "...[截断]";
            }
            
            String logMessage = String.format(
                "💥 [SQL-ERROR] 分类: %s | 方法: %s | 执行时间: %dms | 异常类型: %s | 异常信息: %s | 建议: %s | SQL: %s",
                exceptionType.getDescription(),
                methodId != null ? methodId : "未知",
                executeTimeMs,
                exceptionTypeName,
                exceptionMessage,
                exceptionType.getSuggestion(),
                sqlInfo != null ? sqlInfo : "SQL未知"
            );
            
            // 根据异常分类选择不同的日志级别
            if (isCriticalExceptionType(exceptionType)) {
                log.error(logMessage);
            } else if (isDataAccessExceptionType(exceptionType)) {
                log.warn(logMessage);
            } else {
                log.debug(logMessage);
            }
            
            // 检查是否需要告警
            checkExceptionAlert(exceptionType);
            
        } catch (Exception e) {
            // 记录异常日志时的异常，使用最简单的方式记录
            log.error("记录SQL异常日志时发生异常: {}", e.getMessage());
        }
    }

    /**
     * 检查异常告警
     */
    private void checkExceptionAlert(ExceptionAnalyzer.ExceptionType exceptionType) {
        try {
            // 根据异常类型设置不同的告警阈值
            int threshold = getAlertThreshold(exceptionType);
            
            if (ExceptionAnalyzer.shouldAlert(exceptionType, threshold)) {
                log.error("🚨 [异常告警] 异常类型 {} 在5分钟内出现次数达到告警阈值: {}次，请及时处理！", 
                    exceptionType.getDescription(), threshold);
            }
        } catch (Exception e) {
            log.debug("检查异常告警时发生错误", e);
        }
    }

    /**
     * 获取异常告警阈值
     */
    private int getAlertThreshold(ExceptionAnalyzer.ExceptionType exceptionType) {
        switch (exceptionType) {
            case CONNECTION:
            case DEADLOCK:
                return 3; // 连接和死锁异常阈值较低
            case CONSTRAINT:
            case SYNTAX:
                return 5; // 约束和语法异常中等阈值
            case PERMISSION:
                return 2; // 权限异常阈值很低
            case TIMEOUT:
                return 10; // 超时异常阈值较高
            default:
                return 8; // 默认阈值
        }
    }

    /**
     * 判断是否为关键异常类型
     */
    private boolean isCriticalExceptionType(ExceptionAnalyzer.ExceptionType exceptionType) {
        return exceptionType == ExceptionAnalyzer.ExceptionType.CONNECTION ||
               exceptionType == ExceptionAnalyzer.ExceptionType.DEADLOCK ||
               exceptionType == ExceptionAnalyzer.ExceptionType.PERMISSION;
    }

    /**
     * 判断是否为数据访问异常类型
     */
    private boolean isDataAccessExceptionType(ExceptionAnalyzer.ExceptionType exceptionType) {
        return exceptionType == ExceptionAnalyzer.ExceptionType.CONSTRAINT ||
               exceptionType == ExceptionAnalyzer.ExceptionType.SYNTAX ||
               exceptionType == ExceptionAnalyzer.ExceptionType.DATA;
    }

    /**
     * 判断是否为关键异常
     */
    private boolean isCriticalException(Throwable exception) {
        if (exception == null) {
            return false;
        }
        
        String exceptionName = exception.getClass().getName();
        return exceptionName.contains("SQLException") ||
               exceptionName.contains("DataAccessException") ||
               exceptionName.contains("TransactionException") ||
               exceptionName.contains("ConnectionException") ||
               exception instanceof RuntimeException && 
               exception.getMessage() != null && 
               exception.getMessage().toLowerCase().contains("connection");
    }

    /**
     * 判断是否为数据访问异常
     */
    private boolean isDataAccessException(Throwable exception) {
        if (exception == null) {
            return false;
        }
        
        String exceptionName = exception.getClass().getName();
        return exceptionName.contains("DataIntegrityViolationException") ||
               exceptionName.contains("DuplicateKeyException") ||
               exceptionName.contains("BadSqlGrammarException") ||
               exceptionName.contains("OptimisticLockingFailureException");
    }

    /**
     * 处理SQL执行结果
     */
    private void processExecutionResult(Invocation invocation, String methodId, 
                                       long executeTime, Object result, Throwable exception) {
        try {
            // 更新统计信息
            if (enableStatistics) {
                updateStatistics(methodId, executeTime);
            }
            
            // 记录日志
            boolean isSlow = executeTime >= slowSqlThreshold;
            if (enableSqlLog || isSlow) {
                logSqlExecution(invocation, executeTime, result, exception, isSlow);
            }
        } catch (Exception e) {
            // 确保拦截器本身的异常不影响业务
            log.warn("处理SQL执行结果时发生异常: {}", e.getMessage());
        }
    }

    /**
     * 更新统计信息
     */
    private void updateStatistics(String methodId, long executeTime) {
        if (methodId == null) {
            return;
        }
        
        // 更新总体统计
        totalExecutions.incrementAndGet();
        totalExecutionTime.addAndGet(executeTime);
        
        boolean isSlow = executeTime >= slowSqlThreshold;
        if (isSlow) {
            slowQueryCount.incrementAndGet();
        }
        
        // 更新方法级统计（带缓存大小限制）
        if (sqlStatistics.size() < STATISTICS_CACHE_SIZE) {
            sqlStatistics.computeIfAbsent(methodId, k -> new SqlStatistics())
                        .addExecution(executeTime, isSlow);
        }
    }

    /**
     * 记录SQL执行日志
     */
    private void logSqlExecution(Invocation invocation, long executeTime, 
                                Object result, Throwable exception, boolean isSlow) {
        try {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            Object parameter = invocation.getArgs().length > 1 ? invocation.getArgs()[1] : null;
            
            String methodId = mappedStatement.getId();
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            String sql = formatSql(boundSql.getSql());
            
            if (isSlow) {
                logSlowQuery(invocation, methodId, executeTime, sql, parameter, boundSql, result, exception);
            } else if (enableSqlLog && log.isDebugEnabled()) {
                logNormalQuery(methodId, executeTime, sql, result, exception);
            }
                
        } catch (Exception e) {
            log.warn("记录SQL执行日志失败: {}", e.getMessage());
        }
    }

    /**
     * 记录慢查询日志
     */
    private void logSlowQuery(Invocation invocation, String methodId, long executeTime, String sql, 
                             Object parameter, BoundSql boundSql, Object result, Throwable exception) {
        
        StringBuilder logMessage = new StringBuilder();
        logMessage.append("🐌 [SLOW-SQL] ");
        logMessage.append("Method: ").append(methodId);
        logMessage.append(" | Duration: ").append(executeTime).append("ms");
        logMessage.append(" | Threshold: ").append(slowSqlThreshold).append("ms");
        
        // 添加结果统计
        appendResultInfo(logMessage, result, exception);
        
        // 添加SQL（截断处理）
        logMessage.append(" | SQL: ").append(truncateSql(sql));
        
        // 记录参数（如果启用）
        if (logParameters && parameter != null) {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            String params = getParameterString(parameter, boundSql, mappedStatement);
            if (StringUtils.hasText(params)) {
                logMessage.append(" | Params: ").append(params);
            }
        }
        
        // 根据配置的日志级别输出
        logWithLevel(logMessage.toString());
    }

    /**
     * 记录普通查询日志
     */
    private void logNormalQuery(String methodId, long executeTime, String sql, Object result, Throwable exception) {
        StringBuilder logMessage = new StringBuilder();
        logMessage.append("[SQL-EXEC] ");
        logMessage.append("Method: ").append(methodId);
        logMessage.append(" | Duration: ").append(executeTime).append("ms");
        
        appendResultInfo(logMessage, result, exception);
        logMessage.append(" | SQL: ").append(truncateSql(sql));
        
        log.debug(logMessage.toString());
    }

    /**
     * 添加结果信息
     */
    private void appendResultInfo(StringBuilder logMessage, Object result, Throwable exception) {
        if (exception != null) {
            logMessage.append(" | Status: ERROR(").append(exception.getClass().getSimpleName()).append(")");
        } else {
            logMessage.append(" | Status: SUCCESS");
            if (result instanceof List) {
                logMessage.append(" | Rows: ").append(((List<?>) result).size());
            }
        }
    }

    /**
     * 根据配置的日志级别输出
     */
    private void logWithLevel(String message) {
        switch (logLevel.toUpperCase()) {
            case "ERROR":
                log.error(message);
                break;
            case "WARN":
                log.warn(message);
                break;
            case "INFO":
                log.info(message);
                break;
            default:
                log.debug(message);
        }
    }

    /**
     * 获取SQL参数字符串
     */
    private String getParameterString(Object parameter, BoundSql boundSql, MappedStatement mappedStatement) {
        try {
            List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
            if (parameterMappings == null || parameterMappings.isEmpty()) {
                return parameter != null ? parameter.toString() : "null";
            }

            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            
            StringBuilder params = new StringBuilder();
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                Object value;
                String propertyName = parameterMapping.getProperty();
                
                if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (parameter == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameter.getClass())) {
                    value = parameter;
                } else {
                    MetaObject metaObject = configuration.newMetaObject(parameter);
                    value = metaObject.getValue(propertyName);
                }
                
                if (i > 0) {
                    params.append(", ");
                }
                params.append(formatParameterValue(value));
            }
            
            return params.toString();
        } catch (Exception e) {
            return "参数解析失败: " + e.getMessage();
        }
    }

    /**
     * 格式化参数值
     */
    private String formatParameterValue(Object value) {
        if (value == null) {
            return "null";
        } else if (value instanceof String) {
            return "'" + value + "'";
        } else if (value instanceof Date) {
            return "'" + DATE_FORMAT.format((Date) value) + "'";
        } else {
            return value.toString();
        }
    }

    /**
     * 格式化SQL语句
     */
    private String formatSql(String sql) {
        if (!StringUtils.hasText(sql)) {
            return "";
        }
        try {
            return WHITESPACE_PATTERN.matcher(sql.trim()).replaceAll(" ");
        } catch (Exception e) {
            log.warn("格式化SQL失败: {}", e.getMessage());
            return sql; // 返回原始SQL
        }
    }

    /**
     * 截断SQL字符串
     */
    private String truncateSql(String sql) {
        if (sql == null) {
            return "";
        }
        if (sql.length() <= maxSqlLength) {
            return sql;
        }
        try {
            return sql.substring(0, maxSqlLength) + "...[截断]";
        } catch (Exception e) {
            log.warn("截断SQL失败: {}", e.getMessage());
            return sql.length() > 100 ? sql.substring(0, 100) + "..." : sql;
        }
    }

    /**
     * 获取执行统计信息
     */
    public String getStatisticsReport() {
        StringBuilder report = new StringBuilder();
        report.append("\n=== SQL执行统计报告 ===\n");
        report.append("总执行次数: ").append(totalExecutions.get()).append("\n");
        report.append("慢查询次数: ").append(slowQueryCount.get()).append("\n");
        report.append("总执行时间: ").append(totalExecutionTime.get()).append("ms\n");
        
        long total = totalExecutions.get();
        if (total > 0) {
            report.append("平均执行时间: ").append(totalExecutionTime.get() / total).append("ms\n");
            report.append("慢查询比例: ").append(String.format("%.2f", (double) slowQueryCount.get() / total * 100)).append("%\n");
        }
        
        report.append("\n=== 方法级统计（Top 10） ===\n");
        sqlStatistics.entrySet().stream()
            .sorted((e1, e2) -> Long.compare(e2.getValue().totalTime.get(), e1.getValue().totalTime.get()))
            .limit(10)
            .forEach(entry -> {
                String method = entry.getKey();
                SqlStatistics stats = entry.getValue();
                long timeSinceLastExecution = System.currentTimeMillis() - stats.getLastExecuteTime();
                report.append(String.format("%-60s | 执行次数: %6d | 总时间: %8dms | 平均时间: %6.2fms | 慢查询率: %5.1f%% | 最后执行: %ds前\n",
                    method.length() > 60 ? method.substring(0, 57) + "..." : method,
                    stats.count.get(),
                    stats.totalTime.get(),
                    stats.getAverageTime(),
                    stats.getSlowRatio(),
                    timeSinceLastExecution / 1000));
            });
        
        // 添加异常统计信息
        try {
            String exceptionReport = ExceptionAnalyzer.getStatisticsReport();
            if (exceptionReport != null && !exceptionReport.trim().isEmpty()) {
                report.append(exceptionReport);
            }
        } catch (Exception e) {
            report.append("\n=== 异常统计报告 ===\n");
            report.append("获取异常统计失败: ").append(e.getMessage()).append("\n");
        }
        
        return report.toString();
    }

    /**
     * 获取详细的性能分析报告
     */
    public String getDetailedPerformanceReport() {
        StringBuilder report = new StringBuilder();
        
        // 基础统计
        report.append(getStatisticsReport());
        
        // 性能建议
        report.append("\n=== 性能优化建议 ===\n");
        generatePerformanceSuggestions(report);
        
        return report.toString();
    }

    /**
     * 生成性能优化建议
     */
    private void generatePerformanceSuggestions(StringBuilder report) {
        try {
            long total = totalExecutions.get();
            long slowCount = slowQueryCount.get();
            
            if (total == 0) {
                report.append("暂无SQL执行记录\n");
                return;
            }
            
            double slowRatio = (double) slowCount / total * 100;
            
            // 慢查询比例建议
            if (slowRatio > 10) {
                report.append("⚠️ 慢查询比例过高(").append(String.format("%.1f", slowRatio))
                      .append("%)，建议优化SQL语句和索引\n");
            } else if (slowRatio > 5) {
                report.append("💡 慢查询比例偏高(").append(String.format("%.1f", slowRatio))
                      .append("%)，建议关注性能优化\n");
            } else {
                report.append("✅ 慢查询比例正常(").append(String.format("%.1f", slowRatio)).append("%)\n");
            }
            
            // 执行频率建议
            if (total > 10000) {
                report.append("💡 SQL执行次数较多，建议考虑缓存策略\n");
            }
            
            // 平均执行时间建议
            if (total > 0) {
                long avgTime = totalExecutionTime.get() / total;
                if (avgTime > 100) {
                    report.append("⚠️ 平均执行时间较长(").append(avgTime)
                          .append("ms)，建议优化数据库性能\n");
                }
            }
            
            // 方法级建议
            sqlStatistics.entrySet().stream()
                .filter(entry -> entry.getValue().getSlowRatio() > 20)
                .limit(3)
                .forEach(entry -> {
                    String method = entry.getKey();
                    SqlStatistics stats = entry.getValue();
                    report.append("🎯 重点优化方法: ").append(method)
                          .append(" (慢查询率: ").append(String.format("%.1f", stats.getSlowRatio()))
                          .append("%, 平均耗时: ").append(String.format("%.1f", stats.getAverageTime()))
                          .append("ms)\n");
                });
                
        } catch (Exception e) {
            report.append("生成性能建议时发生错误: ").append(e.getMessage()).append("\n");
        }
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {
        // 慢查询阈值
        String thresholdStr = properties.getProperty("slowSqlThreshold");
        if (StringUtils.hasText(thresholdStr)) {
            try {
                this.slowSqlThreshold = Long.parseLong(thresholdStr);
            } catch (NumberFormatException e) {
                log.warn("无效的慢查询阈值配置: {}, 使用默认值: {}ms", thresholdStr, slowSqlThreshold);
            }
        }
        
        // SQL日志开关
        String enableLogStr = properties.getProperty("enableSqlLog");
        if (StringUtils.hasText(enableLogStr)) {
            this.enableSqlLog = Boolean.parseBoolean(enableLogStr);
        }
        
        // 参数记录开关
        String logParamsStr = properties.getProperty("logParameters");
        if (StringUtils.hasText(logParamsStr)) {
            this.logParameters = Boolean.parseBoolean(logParamsStr);
        }
        
        // 日志级别
        String levelStr = properties.getProperty("logLevel");
        if (StringUtils.hasText(levelStr)) {
            this.logLevel = levelStr.toUpperCase();
        }
        
        // 最大SQL长度
        String maxLengthStr = properties.getProperty("maxSqlLength");
        if (StringUtils.hasText(maxLengthStr)) {
            try {
                this.maxSqlLength = Integer.parseInt(maxLengthStr);
            } catch (NumberFormatException e) {
                log.warn("无效的最大SQL长度配置: {}, 使用默认值: {}", maxLengthStr, maxSqlLength);
            }
        }
        
        // 统计开关
        String enableStatsStr = properties.getProperty("enableStatistics");
        if (StringUtils.hasText(enableStatsStr)) {
            this.enableStatistics = Boolean.parseBoolean(enableStatsStr);
        }
        
        log.info("高性能慢SQL拦截器初始化完成 - 阈值: {}ms, SQL日志: {}, 参数记录: {}, 日志级别: {}, 统计: {}", 
            slowSqlThreshold, enableSqlLog, logParameters, logLevel, enableStatistics);
    }

    // ===== Getter方法 =====
    
    public long getSlowSqlThreshold() { return slowSqlThreshold; }
    public boolean isEnableSqlLog() { return enableSqlLog; }
    public boolean isLogParameters() { return logParameters; }
    public String getLogLevel() { return logLevel; }
    public int getMaxSqlLength() { return maxSqlLength; }
    public boolean isEnableStatistics() { return enableStatistics; }
    public long getTotalExecutions() { return totalExecutions.get(); }
    public long getSlowQueryCount() { return slowQueryCount.get(); }
    public long getTotalExecutionTime() { return totalExecutionTime.get(); }
}
